/**
 * @copyright 2017 Indie Semiconductor.
 *
 * This file is proprietary to Indie Semiconductor.
 * All rights reserved. Reproduction or distribution, in whole
 * or in part, is forbidden except by express written permission
 * of Indie Semiconductor.
 *
 * @file wdt_device.c
 * @Author: Jack.Pan
 * @E-mail:jack.pan@indiemicro.com
 * @Date: 2020/03/18
 */

#include <string.h>
#include <rugbyHP.h>
#include <buck_device.h>
#include <clock_device.h>
#include "errno.h"
#include <isrfuncs.h>
#include <buckOperation.h>

static BuckIsrCallback_t buckIsrCallback = NULL;

/* freqiency: KHz vBuckVolt: 4400- 5400mV*/
void BUCK_Init(BuckOutputVoltage_t enumBuckVolt)
{
    /* Comment the BUCKOPT_SetBuckFreq function for mass production */
    uint16_t version = HWCFG_GetFlashMapVersion();
    if ( (version < 0xA0U) || (version == 0xFFFFU) ){
        BUCKOPT_Init();
        BUCKOPT_SetBuckFreq((uint8_t)BUCK_FREQ_400KHz);
    }
    
    BUCK_INF_SFRS->BUCK_CFG2.SET_VOUT_PD = 1U;
    
    BUCK_INF_SFRS->BUCK_CFG0.VDAC_TRIM          = (uint8_t)enumBuckVolt;

    
    BUCK_INF_SFRS->BUCK_CFG0.RAMP_UPDATE = 0x1U; 
    while(BUCK_INF_SFRS->BUCK_CFG0.RAMP_UPDATE == 1U){}  
    
    BUCK_INF_SFRS->BUCK_CFG6.SSC_ENA      = 1U;
    BUCK_INF_SFRS->BUCK_CFG6.SEL_SSC_STEP = (uint8_t)BUCK_SSC_STEP_8STEPS_1_PEROIDS;
    BUCK_INF_SFRS->BUCK_CFG2.BUCK_ENA     = 1U;                           /* enable buck */
	
    BUCK_INF_SFRS->BUCK_CFG2.SET_VOUT_PD = 0U;
}

void BUCK_RegisterEmergencyIRQ(BuckIsrCallback_t callback)
{
    buckIsrCallback = callback;
    BUCK_INF_SFRS->BUCK_CTRL_INT.ENABLE.INT_VOUT_OC_ENA         = 1U;
    BUCK_INF_SFRS->BUCK_CTRL_INT.ENABLE.INT_VOUT_SHORT_ENA      = 1U;
    BUCK_INF_SFRS->BUCK_CTRL_INT.ENABLE.INT_VIN_UV_ENA          = 1U;
    BUCK_INF_SFRS->BUCK_CTRL_INT.ENABLE.INT_START_ERROR_ENA     = 1U;
    NVIC_EnableIRQ(BUCK_IRQn);
}


void BUCK_Handler(void)
{
    uint8_t status = BUCK_INF_SFRS->BUCK_CTRL_INT.STATUS.BYTE;
    if (buckIsrCallback != NULL){
        buckIsrCallback(status);
    }
    BUCK_INF_SFRS->BUCK_CTRL_INT.CLEAR.BYTE = 0xFFU;
}


void BUCK_DisableBuck(void)
{
    BUCK_INF_SFRS->BUCK_CFG2.SET_VOUT_PD = 1U;
    BUCK_INF_SFRS->BUCK_CFG2.BUCK_ENA = 0U;             /* disable buck */
}

void BUCK_EnableBuck(void)
{
    BUCK_INF_SFRS->BUCK_CFG2.SET_VOUT_PD = 1U;
    BUCK_INF_SFRS->BUCK_CFG2.BUCK_ENA = 1U;             /* enable buck */
    BUCK_INF_SFRS->BUCK_CFG2.SET_VOUT_PD = 0U;
}
